package com.ebocy.hammer.core.init;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.AbstractC2SMessage;

public class MessageLoader {
	private static Logger logger = EbocyLogManager.getSystemLogger();
	private static Map<Short, Class<AbstractC2SMessage>> receiveMessages = new HashMap<Short, Class<AbstractC2SMessage>>();

	public static void initMessage(Class clazz) {
		String url = clazz.getResource("").getPath();
		boolean isInJar = false;
		if (url.indexOf(".jar") != -1) {
			isInJar = true;
		}
		if (isInJar) {
			loadMessageClassInJar(url);
			loadMessageClassInFolder();
		} else {
			loadMessageClassInFolder();
		}
	}

	private static void loadMessageClassInJar(String url) {
		try {
			String jarPaths = url.substring("file:".length(), url.indexOf("!"));
			JarFile file = new JarFile(jarPaths);
			Enumeration<JarEntry> files = file.entries();
			while (files.hasMoreElements()) {
				JarEntry entry = files.nextElement();
				if (entry.getName().indexOf("/message/") != -1 && entry.getName().endsWith(".class")) {
					String className = entry.getName().substring(0, entry.getName().length() - ".class".length()).replace('/', '.');
					Class class1 = Class.forName(className, true, MessageLoader.class.getClassLoader());
					initReceiveMessages(class1);// 初始化所有接受消息
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void loadMessageClass(){
		
	}

	private static void loadMessageClassInFolder() {
		ResourcePatternResolver rl = new PathMatchingResourcePatternResolver();
		try {
			String classPattern = "classpath*:/**/*.class";
			Resource[] resources = rl.getResources(classPattern);
			for (int i = 0; i < resources.length; i++) {
				Resource resource = resources[i];
				String fileName = resource.getURL().toString();
				if (fileName.endsWith(".class")) {
					String className = fileName.substring(fileName.indexOf("classes") + "classes.".length(), fileName.length() - ".class".length()).replace('/', '.');
					// System.out.println(className);
					Class class1 = Class.forName(className, true, MessageLoader.class.getClassLoader());
					initReceiveMessages(class1);// 初始化所有接受消息
				}
			}
		} catch (Exception e) {
			logger.error("加载消息类错误！", e);
			System.exit(0);
		}
	}

	/**
	 * 初始化接收消息
	 */
	private static void initReceiveMessages(Class class1) {
		// 如果声明是接受消息
		if (AbstractC2SMessage.class.isAssignableFrom(class1) && !class1.equals(AbstractC2SMessage.class)) {
			try {
				AbstractC2SMessage receiveMessage = (AbstractC2SMessage) class1.newInstance();
				receiveMessages.put(receiveMessage.getMessageCode(), class1);
			} catch (InstantiationException e) {
				logger.error("初始化消息错误！" + class1.getName(), e);
				System.exit(0);
			} catch (Exception e) {
				logger.error("初始化消息错误！" + class1.getName(), e);
				System.exit(0);
			}
		}
	}

	public static Class<AbstractC2SMessage> getReceiveMessageByCode(short code) {
		return receiveMessages.get(code);
	}

}
